package offer;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Elephas
 * @Date 2022/1/19
 **/
public class InorderTraversal {
    public static void main(String[] args) {

    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        MorrisInorderTraversal(ans,root);
        return ans;
    }
    public void MorrisInorderTraversal(List<Integer> ans,TreeNode root){
        if(root == null){
            return;
        }
        TreeNode current, rightmost;
        current = root;
        while(current != null){
            if(current.left == null){
                ans.add(current.val);
                current = current.right;
            }else{
                rightmost = current.left;
                while(rightmost.right != null && rightmost.right != current){
                    rightmost = rightmost.right;
                }
                if(rightmost.right == current ){
                    rightmost.right = null;
                    ans.add(current.val);
                    current = current.right;
                }else{
                    rightmost.right = current;
                    current = current.left;
                }
            }

        }
    }
}
